package com.zhu.storesmanager.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encoder {

	// 将 s 进行 BASE64 编码
	public static String getBASE64(String s) {
		if (s == null)
			return null;
		BASE64Encoder encoder = new BASE64Encoder();
		try{
			return encoder.encode(s.getBytes("UTF-8"));
		}
		catch (Exception e) {
			return null;
		}
		
	}

	// 将 BASE64 编码的字符串 s 进行解码
	public static String getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b, "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * md5
	 * @param strSrc
	 * @param key
	 * @return
	 */
	public static String MD5Encode(String strSrc) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			//md5.update(strSrc.getBytes("UTF-8"));

			String result = "";
			byte[] temp;
			temp = md5.digest(strSrc.getBytes("UTF-8"));
			
			for (int i = 0; i < temp.length; i++) {
				result += Integer.toHexString((0x000000ff & temp[i]) | 0xffffff00).substring(6);
			}

			return result.toUpperCase();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
